<template>
  <div class="app-container">
    <div style="background-color: #fff;">
      <div class="container-module" style="padding-bottom: 0">
        <el-form :inline="true" class="search-form" size="small">
          <el-row style="display: flex">
            <div style="flex: 1">
              <el-form-item label="类目名称：">
                <el-input
                  v-model="searchForm.name"
                  maxlength="20"
                  show-word-limit
                  onkeyup="value =value.replace(/[^a-zA-Z\u4e00-\u9fa5]/g, '')"
                  placeholder="请输入类目名称"
                  style="width: 260px"
                />
              </el-form-item>
              <el-form-item label="类目状态：">
                <el-select
                  v-model="searchForm.status"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in stateList"
                    :key="index"
                    :label="item.tag_name"
                    :value="item.tag_value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div style="padding: 5px 0">
              <el-form-item>
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-search"
                  @click="getlistWay"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-refresh"
                  @click="resettingWay"
                  >重置</el-button
                >
              </el-form-item>
            </div>
          </el-row>
        </el-form>
      </div>
      <el-divider></el-divider>
      <div style="padding: 0 20px 20px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16">
            <el-button
              v-hasPermi="'goodstype/add'"
              type="primary"
              icon="el-icon-circle-plus-outline"
              size="small"
              @click="addTypeWay"
              >添加类目</el-button
            >
          </el-col>
          <el-col :xs="24" :sm="8">
            <div class="right-panel el-button-group">
              <el-dropdown trigger="click" :hide-on-click="false">
                <span class="el-dropdown-link">
                  <el-button
                    class=""
                    icon="el-icon-s-operation"
                    size="mini"
                  ></el-button>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="fruit in allTableThead"
                    :key="fruit"
                  >
                    <el-checkbox
                      v-model="checkboxTableThead"
                      :label="fruit"
                      >{{ tableTheadOptions[fruit].label }}</el-checkbox
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-col>
          <el-col class="marginTop no_pagination_single_card">
            <el-table
              ref="tablerefs"
              v-loading="loading"
              highlight-current-row
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :data="CategoryList"
              :header-cell-style="{
                'background-color': '#f3f8fe',
                color: '#606266',
                height: '50px',
              }"
              height="100%"
              style="width: 100%"
            >
<el-table-column align="center" prop="id" label="ID">
              </el-table-column>
            <el-table-column
              v-for="fruit in tableThead"
              :key="fruit"
              :label="tableTheadOptions[fruit].label"
              :width="
                tableTheadOptions[fruit].width
                  ? tableTheadOptions[fruit].width + 'px'
                  : 'auto'
              "
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="fruit == 'images'">
                  <div
                    style="
                      width: 30px;
                      height: 30px;
                      border-radius: 5px;
                      overflow: hidden;
                      margin: 0 auto;
                    "
                  >
                    <el-image
                      v-if="scope.row.images"
                      :src="scope.row.images"
                      :preview-src-list="[scope.row.images]"
                    />
                  </div>
                </div>

                <div v-else-if="fruit == 'status'">
                  <div
                    style="margin: 0 3px"
                    v-if="scope.row.status == 1"
                    type="danger"
                    >正常</div
                  >
                  <div v-else style="margin: 0 3px">禁用</div>
                </div>

                <div v-else>
                  <el-tooltip
                    placement="top-start"
                    :content="scope.row[fruit] + ''"
                  >
                    <div class="one_line_hidden">
                      {{ scope.row[fruit] ? scope.row[fruit] : "-" }}
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>



             <!-- <el-table-column align="center" prop="id" label="类目ID">
              </el-table-column>
              <el-table-column align="center" prop="name" label="类目名称">
              </el-table-column>
              <el-table-column align="center" prop="images" label="类目Icon">
                <template slot-scope="scope">
                  <div
                    style="
                      width: 50px;
                      height: 50px;
                      margin: 0 auto;
                      border-radius: 50%;
                      overflow: hidden;
                    "
                  >
                    <el-image
                      style="width: 50px; height: 50px"
                      :src="scope.row.images"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="regionName"
                label="覆盖区域"
              >
                <template slot-scope="scope">
                  {{ scope.row.regionName ? scope.row.regionName : "-" }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="cover_label_name"
                label="覆盖标签"
              >
                <template slot-scope="scope">
                  {{
                    scope.row.cover_label_name
                      ? scope.row.cover_label_name
                      : "-"
                  }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="cover_group_name"
                label="覆盖分组"
              >
                <template slot-scope="scope">
                  {{
                    scope.row.cover_group_name
                      ? scope.row.cover_group_name
                      : "-"
                  }}
                </template>
              </el-table-column>

              <el-table-column align="center" prop="sort" label="排序">
              </el-table-column>
              <el-table-column align="center" prop="status" label="状态">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status == 1">正常</el-tag>
                  <el-tag v-else type="danger">禁用</el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="describe" label="备注">
                <template slot-scope="scope">
                  {{ scope.row.describe ? scope.row.describe : "-" }}
                </template>
              </el-table-column> -->
              <el-table-column
                fixed="right"
                align="center"
                prop="address"
                width="250px"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    v-hasPermi="'goodstype/add'"
                    v-if="scope.row.level !== 3"
                    type="text"

                    @click="addTypeWay(scope.row)"
                  >
                    添加子类目
                  </el-button>
                  <el-button
                    v-hasPermi="'goodstype/edit'"
                    type="text"

                    @click="editTypeWay(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-popconfirm
                    title="这是一段内容确定删除吗？"
                    @confirm="delTypeWay(scope.row)"
                  >
                    <el-button
                      v-hasPermi="'goodstype/del'"
                      style="margin-left: 10px"
                      type="text"

                      slot="reference"
                    >
                      删除
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-drawer
      id="drawer"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="商品类目"
      size="70%"
      :withHeader="false"
      :visible.sync="typeGrouping"
      @close="typeCloseDialog"
      :show-close="true"
    >
      <div style="position: relative" v-loading="submitLoding">
        <div class="drawerTitle" id="drawerTitle">
          <span>商品类目</span>
          <div class="close" @click="typeCloseDialog">
            <i class="el-icon-close" style="font-size:24px;"></i>
          </div>
        </div>
        <el-alert
          id="prompt_explanation"
          class="prompt_explanation"
          title="说明：此类目归属平台的运营类目，商品发布的商品也会依附于【选品池】配置的商品类目"
          type="warning"
          :closable="false"
        >
        </el-alert>
        <el-scrollbar
          wrap-style="overflow-x:hidden;"
          :style="'height:' + reduce"
        >
          <el-form
            v-loading="submitLoding"
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-row style="display: flex; flex-wrap: wrap">

                <el-col :span="22" v-if="superiorname != ''">
                  <el-form-item label="父级类目">
                    <span style="color: #666;font-weight: 600;">{{superiorname}}</span>
                </el-form-item>
                </el-col>

              <el-col :span="22">
                <el-form-item label="类目图标" prop="images">
                  <logo-upload
                    :single-file="iconFile"
                    :show-file-list="false"
                    accept="image/jpeg, image/png"
                    @uploadCallback="logoCallback"
                  /> </el-form-item
              ></el-col>
              <el-col :span="11">
                <el-form-item label="类目名称" prop="name">
                  <el-input
                    type="text"
                    placeholder="请输入类目名称"
                    maxlength="20"
                    show-word-limit
                    v-model="ruleForm.name"
                    autocomplete="off"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="排序" prop="sort">
                  <el-input
                    type="Number"
                    placeholder="请输入排序"
                    v-model="ruleForm.sort"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="11">
                <el-form-item label="状态" prop="status">
                  <el-radio
                    v-for="(item, index) in stateList"
                    :key="index"
                    v-model="ruleForm.status"
                    :label="item.tag_value"
                    >{{ item.tag_name }}</el-radio
                  >
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="是否显示" prop="is_show">
                  <el-radio
                    v-for="(item, index) in [
                      { id: 1, name: '显示' },
                      { id: 2, name: '隐藏' },
                    ]"
                    :key="index"
                    v-model="ruleForm.is_show"
                    :label="item.id"
                    >{{ item.name }}</el-radio
                  >
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="可见用户分组" prop="cover_group">
                  <el-select
                    clearable
                    v-model="ruleForm.cover_group"
                    placeholder="请选择分组"
                  >
                    <el-option
                      v-for="item in groupList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="可见用户省市区" prop="cover_label">
                  <el-cascader
                    v-model="cascaderRegList"
                    style="width: 100%"
                    :options="regionList"
                    collapse-tags
                    :props="{
                      multiple: true,
                      value: 'id',
                      label: 'name',
                      children: 'children',
                      checkStrictly: true,
                    }"
                    clearable
                  ></el-cascader>
                </el-form-item>
              </el-col>

              <el-col :span="22">
                <el-form-item label="可见用户标签" prop="cover_label">
                  <el-select
                    @change="ruleFormUsertagid"
                    style="width: 100%"
                    v-model="tagidList"
                    multiple
                    placeholder="请选择标签"
                  >
                    <el-option-group
                      v-for="group in TagList"
                      :key="group.id"
                      :label="group.category_name"
                    >
                      <el-option
                        v-for="item in group.child"
                        :key="item.id"
                        :label="item.tag_name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="类目备注" prop="describe">
                  <el-input
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入备注"
                    v-model="ruleForm.describe"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-scrollbar>
        <el-row style="margin: 20px 0">
          <el-col :span="24" style="text-align: right; padding-right: 30px"
            ><el-button :loading="submitLoding" @click="typeCloseDialog"
              >取 消</el-button
            >
            <el-button
              :loading="submitLoding"
              type="primary"
              @click="submitForm('ruleForm')"
              >保 存</el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getCategoryList,
  addCategoryList,
  editCategoryList,
  delCategoryList,
} from "@/api/commodity/index";
import { getDictionaryTypeList } from "@/api/index";
import { getgroupList } from "@/api/user/index";
import { getTagCategoryAll, getRegionList } from "@/api/user/index";
import LogoUpload from "@/components/FileUpload";
const tableTheadOption = {
  level:{
    label: "类目层级",
    field: "level",
  },
  images:{
    label: "类目Icon",
    field: "images",
  },
  name:{
    label: "类目名称",
    field: "name",
  },
  regionName:{
    label: "覆盖区域",
    field: "regionName",
  },
  cover_group_name:{
    label: "覆盖分组",
    field: "cover_group_name",
  },
  cover_label_name:{
    label: "覆盖标签",
    field: "cover_label_name",
  },
  sort:{
    label: "排序",
    field: "sort",
  },
  status:{
    label: "状态",
    field: "status",
  },
  describe:{
    label: "备注",
    field: "describe",
  },
  created_at:{
    label: "创建时间",
    field: "created_at",
  },
};
const allTableThead = [
  "level",
  "name",
  "images",
  "regionName",
  "cover_group_name",
  "cover_label_name",
  "sort",
  "status",
  "describe",
  "created_at"
];
const defaultTableThead = [
  "level",
  "name",
 "images",
 "regionName",
 "cover_group_name",
 "cover_label_name",
 "created_at"
 // "sort",
 // "status",
 // "describe"
];


export default {
  components: {
    LogoUpload,
  },
  name: "Orderlist",
  data() {
    return {
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      reduce: 0,
      // 列表加载控制器
      loading: true,
      // 状态列表
      stateList: [],
      // 分组列表
      groupList: [],
      // 标签列表
      TagList: [],
      // 省市区列表
      regionList: [],
      // 搜索参数
      searchForm: {
        name: "",
        status: "",
        page: 1,
        limit: 20,
      },
      // 列表总条数
      total: 0,
      // 类目列表
      CategoryList: [],
      // 添加修改框弹框控制器
      typeGrouping: false,
      // 添加修改弹框标题
      title: "添加类目",
      // 添加参数
      ruleForm: {
        pid: 0,
        name: "",
        describe: "",
        status: 1,
        is_show: 1,
        cover_region_json: "",
        cover_label: "",
        cover_group: "",
        sort: 1,
        images: "",
      },
      // 标签回显数组
      tagidList: [],
      // 省市区回显列表
      cascaderRegList: [],
      // 图片回显
      iconFile: {},
      // 表单验证
      rules: {
        images: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("类目图标不能为空"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                return callback(new Error("类目名称不能为空"));
              } else {
                if (req.test(value)) {
                  return callback(new Error("类目名称不能有数字和特殊字符"));
                } else {
                  callback();
                }
              }
              callback();
            },
            trigger: "change",
          },
        ],
        status: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
      },
      activeName: "first", //订单类型
      activeNames: "five",
      multipleSelection: [],
      tableData: [],
      submitLoding: false,
      superiorname:'',//父级类目
    };
  },
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1; // 为了保证table 每次都会重渲
      this.$nextTick(() => {
        this.$refs.tablerefs.doLayout();
      });
    },
  },
  created() {
    getDictionaryTypeList({ type: "admin_state" }).then((res) => {
      this.stateList = res.data;
    });
    getgroupList().then((res) => {
      this.groupList = res.data.list;
    });
    getTagCategoryAll().then((res) => {
      this.TagList = res.data;
    });
    getRegionList().then((res) => {
      this.regionList = res.data;
    });
    this.getlistWay();
  },
  methods: {
    getlistWay() {
      this.loading = true;
      getCategoryList(this.searchForm)
        .then((res) => {
          this.loading = false;
          this.submitLoding = false;
          if (res.code !== 200 || res.status !== 1) {
            this.$messages.error(res.msg);
            return;
          }
          res.data.forEach((item) => {
            item.regionName = item.cover_region_name_list.toString();
          });
          this.CategoryList = res.data;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 重置搜索参数
    resettingWay() {
      this.searchForm = {
        name: "",
        status: "",
        page: 1,
        limit: 20,
      };
      this.getlistWay();
    },
    // 打开添加类目弹框
    addTypeWay(row) {
      if (row.id) {
        this.ruleForm.pid = row.id;
        this.superiorname = row.name;
      }else{
        this.superiorname = '';
      }
      this.typeGrouping = true;
      this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
    },

    // 点击修改打开添加类目弹框
    editTypeWay(row) {
      if (row.cover_group) {
        row.cover_group = Number(row.cover_group);
      }
      if (row) {
        this.ruleForm = JSON.parse(JSON.stringify(row));
      }
      this.iconFile = {
        url: JSON.parse(JSON.stringify(this.ruleForm.images)),
      };
      this.cascaderRegList = [];
      if (row.cover_region_json) {
        this.cascaderRegList = JSON.parse(row.cover_region_json);
      }
      this.tagidList = [];
      if (row.cover_label) {
        var arr = row.cover_label.split(",");
        arr.forEach((item) => {
          this.tagidList.push(Number(item));
        });
      }
      this.title = "修改类目";
      this.typeGrouping = true;
      this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
    },
    nextTickWay(idName1, idName2, idName3) {
      this.$nextTick(() => {
        var adddialogVisible = document.getElementById(idName1);
        var drawerTitle = document.getElementById(idName2);
        var prompt_explanation = document.getElementById(idName3);
        this.reduce =
          adddialogVisible.offsetHeight -
          (prompt_explanation.offsetHeight + drawerTitle.offsetHeight + 100) +
          "px";
      });
    },
    // 选择标签执行
    ruleFormUsertagid(val) {
      this.ruleForm.cover_label = val.toString();
    },
    // 上传图片回调
    logoCallback(singleFile) {
      this.iconFile = singleFile;
      this.ruleForm.images = singleFile.url;
    },
    // 弹框提交调用
    submitForm(formName) {
      var _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var obj = {
            id: _this.ruleForm.id,
            pid: _this.ruleForm.pid ? _this.ruleForm.pid : "0",
            name: _this.ruleForm.name,
            describe: _this.ruleForm.describe,
            status: _this.ruleForm.status,
            cover_region_json: JSON.stringify(_this.cascaderRegList),
            cover_label: _this.ruleForm.cover_label,
            cover_group: _this.ruleForm.cover_group,
            sort: _this.ruleForm.sort,
            images: _this.ruleForm.images,
            is_show: _this.ruleForm.is_show,
          };
          if (!obj.id) {
            _this.submitLoding = true;
            addCategoryList(obj).then((res) => {
              _this.submitLoding = false;
              if (res.code !== 200 || res.status !== 1) {
                _this.$messages.error(res.msg);
                return;
              }
              if (res.code == 200) {
                _this.$messages.success("添加成功");
                _this.typeGrouping = false;
                _this.typeCloseDialog();
                _this.getlistWay();
              }
            });
          } else {
            _this.submitLoding = true;
            editCategoryList(obj).then((res) => {
              _this.submitLoding = false;
              if (res.code !== 200 || res.status !== 1) {
                _this.$messages.error(res.msg);
                return;
              }
              if (res.code == 200) {
                _this.$messages.success("修改成功");
                _this.typeGrouping = false;
                _this.typeCloseDialog();
                _this.getlistWay();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加修改弹框关闭调用
    typeCloseDialog() {
      this.ruleForm = {
        pid: 0,
        name: "",
        describe: "",
        status: 1,
        is_show: 1,
        cover_region_json: "",
        cover_label: "",
        cover_group: "",
        sort: 1,
        images: "",
      };
      this.iconFile = {};
      this.tagidList = [];
      this.cascaderRegList = [];
      this.$refs.ruleForm.resetFields();
      this.typeGrouping = false;
    },
    // 点击删除 删除当前分类
    delTypeWay(row) {
      this.loading = true;
      let _this = this;
      delCategoryList({ id: row.id }).then((res) => {
        this.loading = false;
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          return;
        }
        if (res.code == 200) {
          _this.$messages.success("删除成功");
          _this.getlistWay();
        } else {
          _this.$messages.error(res.msg);
        }
      });
    },
    //页码
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
  },
};
</script>

<style lang="scss" scoped></style>
